import axios from 'axios';

import {ElMessage} from 'element-plus'
import {useTokenStore} from '@/stores/token.js'
import router from '@/router'

const baseURL = '/api';
const instance = axios.create({baseURL})

instance.interceptors.request.use(
    (config) => {
        const tokenStore = useTokenStore();
        if (tokenStore.token) {
            config.headers.Authorization = tokenStore.token
        }
        return config;
    },
    (err) => {
        Promise.reject(err)
    }
)

export const isLogin = () => {
    const tokenStore = useTokenStore();
    if (!tokenStore.token) {
        return false;
    } else {
        return true;
    }
}

let isLoggedOut = true;
//添加响应拦截器
instance.interceptors.response.use(
    result => {
        //判断业务状态码
        if (result.data.code === 0) {
            return result.data;
        }
        const tokenStore = useTokenStore();
        //操作失败
        //alert(result.data.msg?result.data.msg:'服务异常')
        if (tokenStore.token !== null) {
            ElMessage.error(result.data.message ? result.data.message : '服务异常')
        }
        //异步操作的状态转换为失败
        return Promise.reject(result.data)

    },
    err => {
        //判断响应状态码,如果为401,则证明未登录,提示请登录,并跳转到登录页面
        if (err.response.status === 401 && isLoggedOut) {
            ElMessage.error('请先登录')
            router.push('/StudentSystem/login').then(() => {
                isLoggedOut = false;
            });
        } else {
            if (isLogin()) {
                ElMessage.error('服务异常')
            }
        }

        return Promise.reject(err);//异步的状态转化成失败的状态
    }
)

export default instance;